<template>
  <div class="home-container">
    <!-- 首页Banner -->
    <div class="banner">
      <el-carousel height="300px">
        <el-carousel-item v-for="(item, index) in bannerItems" :key="index">
          <div class="banner-item" :style="{ backgroundImage: `url(${item.image})` }">
            <div class="banner-content">
              <h2>{{ item.title }}</h2>
              <p>{{ item.description }}</p>
              <el-button type="primary" @click="navigateTo(item.link)">{{ item.buttonText }}</el-button>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <el-row :gutter="20" class="main-content">
      <!-- 文章列表区域 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="18" class="article-section">
        <!-- 热门文章 -->
        <div class="section-header">
          <h2>热门文章</h2>
          <router-link to="/articles?sort=hot">查看更多</router-link>
        </div>
        
        <el-skeleton :loading="loading" animated :count="3" v-if="loading">
          <template #template>
            <div class="article-item-skeleton">
              <el-skeleton-item variant="image" style="width: 100px; height: 60px" />
              <div style="flex: 1; margin-left: 20px">
                <el-skeleton-item variant="h3" style="width: 50%" />
                <el-skeleton-item variant="text" style="margin-top: 16px; width: 80%" />
                <el-skeleton-item variant="text" style="width: 60%" />
              </div>
            </div>
          </template>
        </el-skeleton>
        
        <div v-else>
          <div v-for="article in hotArticles" :key="article.id" class="article-item">
            <div class="article-meta">
              <router-link :to="`/board/${article.boardId}`" class="board-tag">
                {{ getBoardName(article.boardId) }}
              </router-link>
              <span class="article-date">{{ formatDate(article.createTime) }}</span>
            </div>
            <router-link :to="`/article/${article.id}`" class="article-title">
              {{ article.title }}
            </router-link>
            <p class="article-summary">{{ article.summary || (article.content ? article.content.substring(0, 100) + '...' : '') }}</p>
            <div class="article-footer">
              <router-link :to="`/user/${article.userId}`" class="article-author">
                <el-avatar :size="24" :src="article.user && article.user.avatarUrl || defaultAvatar"></el-avatar>
                <span>{{ article.user ? article.user.nickname : '未知用户' }}</span>
              </router-link>
              <div class="article-stats">
                <span class="article-date">{{ formatDate(article.createTime) }}</span>
                <span class="article-views"><el-icon><ViewIcon /></el-icon> {{ article.visitCount }}</span>
                <span class="article-comments"><el-icon><ChatDotRound /></el-icon> {{ article.replyCount }}</span>
                <span class="article-likes"><el-icon><Favorite /></el-icon> {{ article.likeCount }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 最新文章 -->
        <div class="section-header">
          <h2>最新文章</h2>
          <router-link to="/articles?sort=new">查看更多</router-link>
        </div>
        
        <el-skeleton :loading="loading" animated :count="5" v-if="loading">
          <template #template>
            <div class="article-item-skeleton">
              <el-skeleton-item variant="image" style="width: 100px; height: 60px" />
              <div style="flex: 1; margin-left: 20px">
                <el-skeleton-item variant="h3" style="width: 50%" />
                <el-skeleton-item variant="text" style="margin-top: 16px; width: 80%" />
                <el-skeleton-item variant="text" style="width: 60%" />
              </div>
            </div>
          </template>
        </el-skeleton>
        
        <div v-else>
          <div v-for="article in newArticles" :key="article.id" class="article-item">
            <div class="article-meta">
              <router-link :to="`/board/${article.boardId}`" class="board-tag">
                {{ getBoardName(article.boardId) }}
              </router-link>
              <span class="article-date">{{ formatDate(article.createTime) }}</span>
            </div>
            <router-link :to="`/article/${article.id}`" class="article-title">
              {{ article.title }}
            </router-link>
            <p class="article-summary">{{ article.summary || (article.content ? article.content.substring(0, 100) + '...' : '') }}</p>
            <div class="article-footer">
              <router-link :to="`/user/${article.userId}`" class="article-author">
                <el-avatar :size="24" :src="article.user && article.user.avatarUrl || defaultAvatar"></el-avatar>
                <span>{{ article.user ? article.user.nickname : '未知用户' }}</span>
              </router-link>
              <div class="article-stats">
                <span class="article-date">{{ formatDate(article.createTime) }}</span>
                <span class="article-views"><el-icon><ViewIcon /></el-icon> {{ article.visitCount }}</span>
                <span class="article-comments"><el-icon><ChatDotRound /></el-icon> {{ article.replyCount }}</span>
                <span class="article-likes"><el-icon><Favorite /></el-icon> {{ article.likeCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      
      <!-- 侧边栏 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="6" class="sidebar">
        <!-- 用户登录信息 -->
        <div class="sidebar-card user-info" v-if="isLoggedIn">
          <div class="user-avatar">
            <el-avatar :size="64" :src="getAvatarUrl(userAvatar) || defaultAvatar"></el-avatar>
            <h3>{{ userName }}</h3>
          </div>
          <div class="user-stats">
            <div class="stat-item">
              <strong>{{ userArticlesCount }}</strong>
              <span>文章</span>
            </div>
            <div class="stat-item">
              <strong>{{ userCommentsCount }}</strong>
              <span>评论</span>
            </div>
            <div class="stat-item">
              <strong>{{ userLikesCount }}</strong>
              <span>获赞</span>
            </div>
          </div>
          <div class="user-actions">
            <router-link to="/article/create">
              <el-button type="primary" size="small">发布文章</el-button>
            </router-link>
            <router-link :to="`/user/${userId}`">
              <el-button size="small">个人主页</el-button>
            </router-link>
          </div>
        </div>
        <div class="sidebar-card login-card" v-else>
          <h3>内容分享创作平台</h3>
          <p>登录后可以发布文章、参与讨论</p>
          <div class="login-actions">
            <router-link to="/login">
              <el-button type="primary">登录</el-button>
            </router-link>
            <router-link to="/register">
              <el-button>注册</el-button>
            </router-link>
          </div>
        </div>
        
        <!-- 热门板块 -->
        <div class="sidebar-card">
          <h3 class="sidebar-title">热门板块</h3>
          <el-skeleton :loading="loading" animated :count="5" v-if="loading">
            <template #template>
              <div style="display: flex; align-items: center; margin-bottom: 10px;">
                <el-skeleton-item variant="circle" style="width: 20px; height: 20px" />
                <el-skeleton-item variant="text" style="margin-left: 10px; width: 40%" />
              </div>
            </template>
          </el-skeleton>
          
          <ul class="board-list" v-else>
            <li v-for="board in boards" :key="board.id">
              <router-link :to="`/board/${board.id}`">
                {{ board.name }}
                <span class="count">({{ board.articleCount || 0 }})</span>
              </router-link>
            </li>
          </ul>
        </div>
        
        <!-- 活跃用户 -->
        <div class="sidebar-card">
          <h3 class="sidebar-title">活跃用户</h3>
          <el-skeleton :loading="loading" animated :count="5" v-if="loading">
            <template #template>
              <div style="display: flex; align-items: center; margin-bottom: 16px;">
                <el-skeleton-item variant="circle" style="width: 32px; height: 32px" />
                <div style="margin-left: 16px; flex: 1;">
                  <el-skeleton-item variant="text" style="width: 50%" />
                  <el-skeleton-item variant="text" style="width: 30%" />
                </div>
              </div>
            </template>
          </el-skeleton>
          
          <div class="active-users" v-else>
            <router-link 
              v-for="user in activeUsers" 
              :key="user.id" 
              :to="`/user/${user.id}`" 
              class="user-item"
            >
              <el-avatar :size="32" :src="user.avatarUrl ? getAvatarUrl(user.avatarUrl) : defaultAvatar"></el-avatar>
              <div class="user-info-mini">
                <span class="username">{{ user.nickname }}</span>
                <span class="articles-count">{{ user.articleCount }}篇文章</span>
              </div>
            </router-link>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { View as ViewIcon, ChatDotRound, Star as Favorite } from '@element-plus/icons-vue'
import moment from 'moment'
import api from '@/api'
import config from '@/config'

export default {
  name: 'Home',
  components: {
    ViewIcon,
    ChatDotRound,
    Favorite
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const loading = ref(true)
    const defaultAvatar = require('@/assets/default-avatar.png')
    
    // 文章数据
    const hotArticles = ref([])
    const newArticles = ref([])
    
    // 活跃用户
    const activeUsers = ref([])
    
    // 轮播图数据
    const bannerItems = ref([
      {
        title: '欢迎来到内容分享创作平台',
        description: '这里是技术爱好者的交流平台',
        image: require('@/assets/banner1.jpg'),
        link: '/articles',
        buttonText: '浏览文章'
      },
      {
        title: '分享你的知识',
        description: '记录所学，分享所得',
        image: require('@/assets/banner2.jpg'),
        link: '/article/create',
        buttonText: '发布文章'
      },
      {
        title: '加入我们的社区',
        description: '与志同道合的开发者一起成长',
        image: require('@/assets/banner3.jpg'),
        link: '/register',
        buttonText: '立即注册'
      }
    ])
    
    // 用户信息
    const isLoggedIn = computed(() => store.getters['user/isLoggedIn'])
    const userId = computed(() => store.getters['user/userId'] || null)
    const userName = computed(() => store.getters['user/userName'])
    const userAvatar = computed(() => store.getters['user/userAvatar'])
    
    // 用户统计
    const userArticlesCount = ref(0)
    const userCommentsCount = ref(0)
    const userLikesCount = ref(0)
    
    // 板块信息
    const boards = computed(() => store.state.boards)
    
    // 获取板块名称
    const getBoardName = (boardId) => {
      const board = boards.value.find(b => b.id === boardId)
      return board ? board.name : '未知板块'
    }
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '未知日期';
      
      const now = moment();
      const postDate = moment(date);
      const diff = now.diff(postDate, 'days');
      
      if (diff < 1) {
        // 不到一天显示"今天"或具体小时
        const hourDiff = now.diff(postDate, 'hours');
        if (hourDiff < 1) {
          const minuteDiff = now.diff(postDate, 'minutes');
          return minuteDiff <= 0 ? '刚刚' : `${minuteDiff}分钟前`;
        }
        return `${hourDiff}小时前`;
      } else if (diff < 7) {
        // 不到一周显示"X天前"
        return `${diff}天前`;
      } else {
        // 超过一周显示具体日期
        return postDate.format('YYYY-MM-DD');
      }
    }
    
    // 页面跳转
    const navigateTo = (path) => {
      router.push(path)
    }
    
    // 获取活跃用户
    const fetchActiveUsers = async () => {
      try {
        const response = await api.user.getActiveUsers(5);
        if (response.code === 0 && response.data) {
          // 返回的数据需要转换为符合我们界面要求的格式
          activeUsers.value = response.data.map(user => ({
            id: user.id,
            nickname: user.nickname,
            avatarUrl: user.avatarUrl, // 确保使用正确的字段名
            articleCount: user.articleCount || 0
          }));
        } else {
          console.error('获取活跃用户失败:', response);
          useDefaultActiveUsers();
        }
      } catch (error) {
        console.error('获取活跃用户接口异常:', error);
        useDefaultActiveUsers();
      }
    };
    
    // 使用默认的活跃用户数据
    const useDefaultActiveUsers = () => {
      activeUsers.value = [
        { id: 1, nickname: '技术达人', avatar: '', articleCount: 42 },
        { id: 2, nickname: '前端小王子', avatar: '', articleCount: 38 },
        { id: 3, nickname: '全栈工程师', avatar: '', articleCount: 27 },
        { id: 4, nickname: 'Vue大神', avatar: '', articleCount: 23 },
        { id: 5, nickname: '热心社区用户', avatar: '', articleCount: 19 }
      ];
    };
    
    // 处理头像URL
    const getAvatarUrl = (url) => {
      if (!url) return defaultAvatar;
      return config.getAvatarUrl(url);
    }
    
    // 初始化数据
    onMounted(async () => {
      // 获取板块列表 - 公共数据，无需登录
      if (boards.value.length === 0) {
        await store.dispatch('fetchBoards');
      }
      
      try {
        loading.value = true;
        
        // 获取热门文章 - 公共数据，无需登录
        const hotResponse = await store.dispatch('fetchArticles', {
          page: 1,
          size: 5,
          sort: 'hot'  // 按访问量排序
        });
        hotArticles.value = hotResponse || [];
        
        // 获取最新文章 - 公共数据，无需登录
        const newResponse = await store.dispatch('fetchArticles', {
          page: 1,
          size: 5,
          sort: 'new'  // 按发布时间排序
        });
        newArticles.value = newResponse || [];
        
        // 获取活跃用户列表 - 公共数据，无需登录
        await fetchActiveUsers();
        
        // 仅当用户已登录时获取用户统计数据
        if (isLoggedIn.value) {
          try {
            // 获取用户统计数据
            const userInfo = await api.user.getInfo();
            if (userInfo && userInfo.code === 0 && userInfo.data) {
              userArticlesCount.value = userInfo.data.articleCount || 0;
              userCommentsCount.value = userInfo.data.commentCount || 0;
              userLikesCount.value = userInfo.data.likeCount || 0;
            }
          } catch (error) {
            console.error('获取用户统计数据失败:', error);
            // 出错时重置为0
            userArticlesCount.value = 0;
            userCommentsCount.value = 0;
            userLikesCount.value = 0;
          }
        } else {
          // 未登录状态下，不需要设置这些值，因为未登录状态下不会显示这个组件
          userArticlesCount.value = 0;
          userCommentsCount.value = 0;
          userLikesCount.value = 0;
        }
      } catch (error) {
        console.error('获取首页数据失败:', error);
      } finally {
        loading.value = false;
      }
    })
    
    return {
      loading,
      defaultAvatar,
      hotArticles,
      newArticles,
      activeUsers,
      bannerItems,
      isLoggedIn,
      userId,
      userName,
      userAvatar,
      userArticlesCount,
      userCommentsCount,
      userLikesCount,
      boards,
      getBoardName,
      formatDate,
      navigateTo,
      getAvatarUrl
    }
  }
}
</script>

<style scoped>
.home-container {
  padding: 0 15px;
}

.banner {
  margin-bottom: 30px;
  border-radius: 8px;
  overflow: hidden;
}

.banner-item {
  height: 100%;
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  padding: 0 50px;
}

.banner-content {
  max-width: 500px;
  color: white;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}

.banner-content h2 {
  font-size: 32px;
  margin-bottom: 10px;
}

.banner-content p {
  font-size: 18px;
  margin-bottom: 20px;
}

.main-content {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.section-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.section-header a {
  font-size: 14px;
  color: #409EFF;
  text-decoration: none;
}

.article-item {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 0;
}

.article-item:last-child {
  border-bottom: none;
}

.article-meta {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.board-tag {
  display: inline-block;
  background-color: #f0f9eb;
  color: #67c23a;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  text-decoration: none;
  margin-right: 10px;
}

.article-date {
  font-size: 12px;
  color: #909399;
}

.article-title {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  text-decoration: none;
}

.article-title:hover {
  color: #409EFF;
}

.article-summary {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.article-author {
  display: flex;
  align-items: center;
  text-decoration: none;
}

.article-author span {
  margin-left: 8px;
  font-size: 14px;
  color: #606266;
}

.article-stats {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 13px;
  color: #909399;
}

.article-views, .article-comments, .article-likes {
  display: flex;
  align-items: center;
  gap: 4px;
}

.article-views .el-icon, .article-comments .el-icon, .article-likes .el-icon {
  margin-right: 2px;
}

.sidebar {
  padding-top: 10px;
}

.sidebar-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.sidebar-title {
  font-size: 18px;
  color: #303133;
  margin-top: 0;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.user-info {
  text-align: center;
}

.user-avatar {
  margin-bottom: 15px;
}

.user-avatar h3 {
  margin-top: 10px;
  margin-bottom: 0;
  font-size: 16px;
  color: #303133;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-item strong {
  font-size: 18px;
  color: #303133;
}

.stat-item span {
  font-size: 12px;
  color: #909399;
}

.user-actions {
  display: flex;
  justify-content: space-around;
}

.login-card {
  text-align: center;
}

.login-card h3 {
  margin-top: 0;
  color: #303133;
}

.login-card p {
  color: #606266;
  margin-bottom: 20px;
}

.login-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.board-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.board-list li {
  margin-bottom: 10px;
}

.board-list li a {
  color: #606266;
  text-decoration: none;
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f5f7fa;
}

.board-list li a:hover {
  color: #409EFF;
}

.board-list .count {
  color: #909399;
  font-size: 12px;
}

.active-users {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.user-item {
  display: flex;
  align-items: center;
  text-decoration: none;
  padding: 5px 0;
}

.user-info-mini {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
}

.user-info-mini .username {
  font-size: 14px;
  color: #303133;
}

.user-info-mini .articles-count {
  font-size: 12px;
  color: #909399;
}

.article-item-skeleton {
  display: flex;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .banner-content {
    padding: 0 20px;
  }
  
  .banner-content h2 {
    font-size: 24px;
  }
  
  .banner-content p {
    font-size: 14px;
  }
  
  .sidebar {
    margin-top: 20px;
  }
}
</style> 